//
//  NSURLConnection+Sync.m
//  YDGJ
//
//  Created by ydcq on 16/8/19.
//  Copyright © 2016年 Galaxy360. All rights reserved.
//

#import "NSURLConnection+Sync.h"

@implementation NSURLConnection (Sync)

+ (void)sendSyncRequestWithUrl:(NSString *)url method:(NSString *)method parameters:(NSDictionary *)dict completionBlock:(void (^)(RequestResult,id))resultBlock
{
    NSLog(@"开始发送同步请求\n%@\n",url);
    NSLog(@"参数\n%@\n",dict);
    if (method.length==0) {
        method = @"GET";
    }
    if (dict&&dict.allKeys.count>0) {
        if ([method isEqualToString:@"GET"]) {
            int count=0;
            for (NSString *key in dict) {
                if (count==0) {
                    url = [url stringByAppendingString:@"?"];
                }
                if (count==0) {
                    url = [url stringByAppendingFormat:@"%@=%@",key,dict[key]];
                }
                else {
                    url = [url stringByAppendingFormat:@"&%@=%@",key,dict[key]];
                }
                count++;
            }
        }
    }
    NSURL *url_ = [NSURL URLWithString:url];
    NSMutableURLRequest *mReq = [NSMutableURLRequest requestWithURL:url_];
    [mReq setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    if ([method isEqualToString:@"POST"]) {
        [mReq setHTTPMethod:@"POST"];
        [mReq setHTTPBody:[NSJSONSerialization dataWithJSONObject:dict options:0 error:nil]];
    }
    [mReq setTimeoutInterval:15];
    NSURLResponse *rsp;NSError *error;
    NSData *data = [self sendSynchronousRequest:mReq returningResponse:&rsp error:&error];
    if (!resultBlock) {
        return;
    }
    if (error) {
        NSLog(@"同步请求结果：%@",error);
        resultBlock(RequestResultFail,error);
    }
    else if(data) {
        NSDictionary *dict_ = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"同步请求结果：%@",dict_);
        int code = [dict_[@"code"] intValue];
        resultBlock(code==0?RequestResultSuccess:RequestResultFail,dict_);
    }
}

@end
